use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .create_table(
                Table::create()
                    .table(TaxRules::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(TaxRules::Id)
                            .string()
                            .not_null()
                            .primary_key(),
                    )
                    .col(ColumnDef::new(TaxRules::TaxClassId).string().not_null())
                    .col(ColumnDef::new(TaxRules::TaxRateId).string().not_null())
                    .col(ColumnDef::new(TaxRules::Priority).integer().not_null())
                    .col(
                        ColumnDef::new(TaxRules::CreatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .col(
                        ColumnDef::new(TaxRules::UpdatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk_tax_rules_tax_class_id")
                            .from(TaxRules::Table, TaxRules::TaxClassId)
                            .to(TaxClasses::Table, TaxClasses::Id)
                            .on_delete(ForeignKeyAction::Cascade)
                            .on_update(ForeignKeyAction::Restrict),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk_tax_rules_tax_rate_id")
                            .from(TaxRules::Table, TaxRules::TaxRateId)
                            .to(TaxRates::Table, TaxRates::Id)
                            .on_delete(ForeignKeyAction::Cascade)
                            .on_update(ForeignKeyAction::Restrict),
                    )
                    .to_owned(),
            )
            .await
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .drop_table(Table::drop().table(TaxRules::Table).to_owned())
            .await
    }
}

#[derive(DeriveIden)]
enum TaxRules {
    Table,
    Id,
    TaxClassId,
    TaxRateId,
    Priority,
    CreatedAt,
    UpdatedAt,
}

#[derive(DeriveIden)]
enum TaxClasses {
    Table,
    Id,
}

#[derive(DeriveIden)]
enum TaxRates {
    Table,
    Id,
}
